package com.jse.util.concurrent.old.notify;

/**
 * wait线程必须等到前面线程的notify之后，线程并且执行完run方法才激活
 * @author zenghua233
 *
 */
public class NotifyTest {
	public Object obj = new Object();
	
	public static void main(String[] args) throws Exception {
		NotifyTest t = new NotifyTest();
		t.testWaitNotify();
	}
	
	/**
	 * wait与notify方法必须要作用于代码块的监控对象
	 * 
	 * 这里代码块锁定的是Object，所以监控对象是obj，应该调用监控对象的wait、notify
	 * @throws Exception
	 */
	public void testWaitNotify() throws Exception {
		new Thread(new ThreadA()).start();
		Thread.sleep(1000);
		new Thread(new ThreadB()).start();
	}
	
	class ThreadA implements Runnable {
		
		public ThreadA() {}

		@Override
		public void run() {
			synchronized(obj) {
				try {
					obj.wait();
					System.out.println("ThreadA被唤醒");
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
		
	}
	
	class ThreadB implements Runnable {

		@Override
		public void run() {
			synchronized (obj) {
				System.out.println("ThreadB执行notify");
				obj.notify();
				
				try {
					Thread.sleep(1000);
					System.out.println("ThreadB执行完毕");
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		
	}
}
